﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using MicropleSoft.WmsServiceLibrary.ServiceFactory;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace MicropleSoft.WmsServiceLibrary.BaseDataService
{
    public class BaseDataWrapBuilder : IBaseDataWrapBuilder
    {
        private readonly Database _db = ServiceFactoryCreator.CreateAbstractServiceFactory().CreateDatabase();
        public BaseDataWrap Build(string dataSourceKey,string whId,string condition)
        {
            var baseDataWrap = new BaseDataWrap();
            baseDataWrap.PBaseDataWrapType = BaseDataWrapType.Server;
            //先去表数据
            //然后赋别的变量

            var list = BaseDataConfigEntity.GetBaseDataConfigEntityList().Where(entity => entity.Key == dataSourceKey);
            if (list.Count() == 0)
                throw new Exception("不存在基础数据配置Key：" + dataSourceKey);
         
            baseDataWrap.DataKey = list.First().Key;

            string sql = String.Format(list.First().Sql, whId);
            if(condition.Trim().ToUpper().StartsWith("AND "))
            {
                sql = sql + condition;
            }
            else
            {
                sql = sql + " and " + condition;
            }

            baseDataWrap.BaseDataSource = _db.ExecuteDataSet(CommandType.Text, sql).Tables[0];

            baseDataWrap.LookUpViewHeaderList = list.First().LookUpViewHeaderList;

            return baseDataWrap;
        }
    }
}
